package com.jsg.sl651.manager;

import com.jsg.sl651.entity.frame.FrameMessageWrapper;
import com.jsg.sl651.entity.frame.header.MessageHeader;
import io.netty.channel.Channel;
import io.netty.util.AttributeKey;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ChannelInstanceManager {
    //消息流水号 存储到ChannelHandlerContext里面
    private static final AttributeKey<Integer> FLOW_NUMBER = AttributeKey.newInstance("FlowNumber");
    private static final AttributeKey<Integer> IS_CONNECT = AttributeKey.newInstance("IsConnect");
    private static final AttributeKey<String> CLIENT_ID = AttributeKey.newInstance("ClientId");
    private static final Map<String, Channel> CHANNEL_MAP = new ConcurrentHashMap<>();
    private static final Map<String, MessageHeader> MESSAGE_HEADER_MAP = new ConcurrentHashMap<>();

    public static void initAttribute(Channel channel) {
        channel.attr(FLOW_NUMBER).set(0);
        channel.attr(IS_CONNECT).set(0);
    }

    public static void updateAttribute(Channel channel, int flowNumber, int isConnect) {
        channel.attr(FLOW_NUMBER).set(flowNumber);
        channel.attr(IS_CONNECT).set(isConnect);
    }


    public static boolean isNewConnect(Channel channel) {
        return channel.attr(IS_CONNECT).get() == 0;
    }


    public static int getFlowNumber(Channel channel) {
        int flowNumber = channel.attr(FLOW_NUMBER).get() + 1;
        channel.attr(FLOW_NUMBER).set(flowNumber);
        return flowNumber;
    }


    public static void removeChannel(Channel channel) {
        String hex = channel.attr(CLIENT_ID).get();
        if (hex == null || hex.isEmpty()) {
            return;
        }
        CHANNEL_MAP.remove(hex);
        MESSAGE_HEADER_MAP.remove(hex);
    }

    public static void addChannel(Channel channel, FrameMessageWrapper frameMessageWrapper) {
        channel.attr(CLIENT_ID).set(frameMessageWrapper.getHeader().getRemoteTelemetryStationAddress().getMessageHex());
        CHANNEL_MAP.put(frameMessageWrapper.getHeader().getRemoteTelemetryStationAddress().getMessageHex(), channel);
        MESSAGE_HEADER_MAP.put(frameMessageWrapper.getHeader().getRemoteTelemetryStationAddress().getMessageHex(), frameMessageWrapper.getHeader());
    }

    public static String getClientId(Channel channel) {
        return channel.attr(CLIENT_ID).get();
    }

    public static MessageHeader getDefaultHeader(String clientId) {
        return MESSAGE_HEADER_MAP.get(clientId);
    }

    public static boolean validClientId(String clientId, Channel channel) {
        return clientId.equals(channel.attr(CLIENT_ID).get());
    }

}
